<template>
  <view class="layout">
    <!-- 导航栏 -->
    <view class="navbar" :class="{ 'nav-sticky': isSticky }">
      <view class="statusBar" :style="{ height: getStatusBarHeight() + 'px' }"></view>
      <view class="titleBar" :style="{ height: getTitleBarHeight() + 'px', marginLeft: getLeftIconLeft() + 'px' }">
        <view class="search-container">
          <view class="search" @click="handleSearchClick">
            <uni-icons class="icon" type="search" color="#888" size="18"></uni-icons>
            <text class="text">搜索</text>
          </view>
          <button class="ai-btn" @click="AiSearch">
            <uni-icons class="ai-icon" type="robot" color="#fff" size="20"></uni-icons>
            <span class="ai-text">AI搜索</span>
          </button>
        </view>
      </view>
    </view>
    <view class="fill" :style="{ height: getNavBarHeight() - 20 + 'px' }"></view>
    
    <!-- 内容区域 -->
    <scroll-view 
      class="content-scroll" 
      scroll-y 
      @scroll="handleScroll"
      @scrolltolower="handleReachBottom"
      :style="{ height: contentHeight + 'px' }"
    >
      <view class="content">
        <!-- 轮播图 -->
        <view class="recommendation">
          <view class="swiper-container">
            <swiper class="swiper" :autoplay="autoplay" :interval="interval" :duration="duration">
              <swiper-item v-for="(val, index) in list" :key="index">
                <view class="swiper-item">
                  <image :src="val" mode="aspectFit"></image>
                </view>
              </swiper-item>
            </swiper>
          </view>
          
          <!-- 分类标签 -->
          <view class="tag-list">
            <view class="tag-item" @click="goRanking">
              <image src="/static/novel/menu1.png"></image>
              <text>排行榜</text>
            </view>
            <view class="tag-item" @click="goClassify">
              <image src="/static/novel/menu2.png"></image>
              <text>分类</text>
            </view>
            <view class="tag-item" @click="goNewBook">
              <image src="/static/novel/menu3.png"></image>
              <text>新书</text>
            </view>
            <view class="tag-item" @click="goBookself">
              <image src="/static/novel/book.png"></image>
              <text>书架</text>
            </view>
          </view>
          
          <!-- 热门标签及小说列表 -->
          <view class="hot-section">
            <view class="hot-header">
              <text class="hot-title">热门分类</text>
              <text class="hot-more" @click="goMoreTags">更多</text>
            </view>
            <scroll-view
              class="tag-scroll"
              scroll-x
              :show-scrollbar="false"
              style="white-space: nowrap;"
            >
              <view
                class="tag-item"
                :class="{ active: tag === currentTag }"
                v-for="(tag, index) in hotTags"
                :key="index"
                @click="handleTagClick(tag)"
              >
                <text>{{ tag }}</text>
              </view>
            </scroll-view>
            
            <view class="novel-grid">
              <view class="novel-item" v-for="(novel, idx) in hotNovels" :key="idx" @click="goRead(novel.novelId)">
                <view class="novel-cover-container">
                  <view 
                    class="hot-rank" 
                    :class="[
                      idx === 0 ? 'rank1' : 
                      idx === 1 ? 'rank2' : 
                      idx === 2 ? 'rank3' : 'rank-other'
                    ]"
                  >
                    {{ idx + 1 }}
                  </view>
                  <image class="novel-cover" :src="novel.image" mode="widthFix"></image>
                </view>
                <view class="novel-info">
                  <text class="novel-name">{{ novel.novelName }}</text>
                  <text class="author">{{ novel.author }}</text>
                  <text class="novel-status">{{ novel.status }} · {{ novel.count / 10000 }}万</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 排行榜 -->
          <view class="book_list">
            <view class="title">
              排行榜
              <view class="more" @click="goRanking">更多</view>
            </view>
            <view class="scroll-view">
              <scroll-view class="scroll-view_H" scroll-x scroll-left="0">
                <view class="scroll-view-item_H" v-for="(val, index) in books" :key="index" @click="goRead(val.novelId)">
                  <view class="img_box">
                    <view class="ranking" :class="{ one: index === 0, two: index === 1, three: index === 2 }">
                      <view class="icon"><uni-icons type="vip-filled" /></view>
                      TOP&nbsp;{{ index + 1 }}
                    </view>
                    <image :src="val.image"></image>
                  </view>
                  <view class="name">{{ val.novelName }}</view>
                  <view class="author">{{ val.author }}</view>
                </view>
              </scroll-view>
            </view>
          </view>
          
          <!-- 限时免费 -->
          <view class="book_list">
            <view class="title">
              限时免费
              <uni-countdown
                :day="0"
                :hour="11"
                :minute="59"
                :second="59"
                :showDay="false"
                color="#333"
                backgroundColor="#fff"
                splitorColor="#ff5500"
                @timeup="handleTimeUp"
                style="margin-left: 10px;"
              ></uni-countdown>
              <view class="more" @click="goFree">更多</view>
            </view>
            <view class="scroll-view">
              <scroll-view class="scroll-view_H" scroll-x scroll-left="0">
                <view
                  class="scroll-view-item_H"
                  v-for="(val, index) in FreeBooks"
                  :key="index"
                  @click="goRead(val.novelId)"
                >
                  <view class="img_box">
                    <view class="free-label">免费</view>
                    <image :src="val.image" mode="widthFix" lazy-load border-radius="6rpx"></image>
                  </view>
                  <view class="name">{{ val.novelName }}</view>
                  <view class="author">{{ val.author }}</view>
                </view>
              </scroll-view>
            </view>
          </view>
          
          <!-- 猜你喜欢区域 -->
          <view class="guess-like-section">
            <view class="guess-header">
              <text class="guess-title">猜你喜欢</text>
              <view class="setting-btn" @click="isDrawerOpen = true">
                设置阅读喜好
              </view>
            </view>
            <view class="novel-list">
              <view class="novel-item" v-for="(novel, idx) in guessNovels" :key="idx" @click="goRead(novel.novelId)">
                <image class="novel-cover" :src="novel.image" mode="widthFix"></image>
                <view class="novel-info">
                  <view class="title-row">
                    <text class="novel-name">{{ novel.novelName }}</text>
                    <text class="novel-score">{{ novel.score }}分</text>
                  </view>
                  <text class="novel-desc">{{ novel.des }}</text>
                  <view class="bottom-row">
                    <text class="novel-status">{{ novel.status }} · {{ novel.count / 10000 }}万</text>
                    <view class="novel-tags">
                      <text class="tag">{{ novel.name }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 阅读喜好抽屉 -->
    <view class="drawer" :class="{ 'drawer-open': isDrawerOpen }">
      <view class="drawer-content">
        <view class="drawer-header">
          <text class="drawer-title">选择阅读喜好</text>
          <view class="close-btn" @click="isDrawerOpen = false">×</view>
        </view>
        <view class="genre-list">
          <view 
            class="genre-item" 
            v-for="(genre, index) in genres" 
            :key="index"
            @click="handleGenreClick(genre)"
          >
            {{ genre }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from '@/utils/system.js'
import {ApiGetBanners, ApigetCategroyTags, ApiGetFreeNovels, ApiGetLike, ApigetRankNovels, ApiGetCategroyNovels, ApigetHotCateGroyByType} from "../../pages/api/novel.js"
import {ApiSetNovel} from "../../pages/api/user.js"

const contentHeight = computed(() => {
  return uni.getSystemInfoSync().windowHeight - getNavBarHeight()
})

const autoplay = ref(true)
const interval = ref(3000)
const duration = ref(500)
const list = ref([])

// 获取所有的轮播图
const getAllBanners = async() => {
  let res = await ApiGetBanners()
  list.value = res
}

// 排行榜数据
const books = ref([])
const getRank = async() => {
  let res = await ApigetRankNovels()
  books.value = res
}

// 免费小说
const FreeBooks = ref([])
const getFree = async() => {
  let res = await ApiGetFreeNovels()
  FreeBooks.value = res
}

const isSticky = ref(false)
const isSearchActive = ref(false)
const currentTag = ref(null) // 当前选中标签

const hotTags = ref([])
// 获取热门标签
const getHotTags = async() => {
  let res = await ApigetCategroyTags()
  hotTags.value = res
  genres.value = res
}

// 获取热门标签数据
const hotNovels = ref([])
const getHotNovels = async() => {
  let res = await ApiGetCategroyNovels()
  hotNovels.value = res
}
const pageNum = ref(1)
const size = ref(15)
const isLoading = ref(false)
// 获取喜欢数据
const guessNovels = ref([])
const getLike = async() => {
  if (isLoading.value) {
    return
  }
  try {
    isLoading.value = true
    let res = await ApiGetLike(pageNum.value, size.value)
    if (pageNum.value === 1) {
      guessNovels.value = res
    } else {
      guessNovels.value = [...guessNovels.value, ...res]
    }
  } catch (err) {
    console.error('获取猜你喜欢数据失败:', err)
  } finally {
    isLoading.value = false
  }
}

// 新增抽屉相关变量
const isDrawerOpen = ref(false)
const genres = ref([])

onMounted(() => {
  // 获取所有的轮播图
  getAllBanners()
  // 获取热门标签
  getHotTags()
  // 获取热门标签数据
  getHotNovels()
  // 获取排行榜数据
  getRank()
  // 获取限时免费
  getFree()
  // 获取猜你喜欢
  getLike()
})

// 仅保留组件的滚动事件处理
const handleScroll = (e) => {
  isSticky.value = e.detail.scrollTop > 300
}

const handleSearchClick = () => {
  isSearchActive.value = true
  setTimeout(() => {
    isSearchActive.value = false
  }, 200)
  uni.navigateTo({
    url:"/pages/novel/search"
  })
}

// 获取热门数据
const handleTagClick = async(tag) => {
  currentTag.value = tag
  let res = await ApigetHotCateGroyByType(tag)
  hotNovels.value = res
}

const goRanking = () => {
  uni.navigateTo({
    url:"/pages/novel/rank"
  })
}

const goClassify = () => {
  uni.navigateTo({
    url:"/pages/novel/classify"
  })
}

const goNewBook = () => {
  uni.navigateTo({
    url:"/pages/novel/newBook"
  })
}

const goBookself = () => {
  uni.navigateTo({
    url:"/pages/novel/bookSelf"
  })
}

const goRead = (bookId) => {
  uni.navigateTo({
    url:`/pages/novel/bookCover?bookId=` + bookId
  })
}

const handleTimeUp = () => {
  uni.navigateTo({
    url:"/pages/novel/free"
  })
}

const goMoreTags = () => {
  uni.navigateTo({
    url:"/pages/novel/classify"
  })
}

// 限时免费
const goFree = () => {
    uni.navigateTo({
      url:"/pages/novel/free"
    })
}

const AiSearch = () => {
  uni.navigateTo({
    url:"/pages/novel/AiSearch"
  })
}

// 新增标签点击处理
const handleGenreClick = async(genre) => {
  isDrawerOpen.value = false
  await ApiSetNovel(genre)
  // 显示成功提示
  uni.showToast({
    title: '设置成功',
    icon: 'none',
    duration: 2000
  })
}

// 触底加载更多
const handleReachBottom = () => {
  // 判断是否还有数据可加载
  if (guessNovels.value.length === size.value * pageNum.value) {
    pageNum.value += 1
    getLike()
  }
}
</script>

<style lang="scss" scoped>
:root {
  --status-bar-height: 20px;
  --nav-bar-height: 80px;
}

.layout {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 50;
  background: linear-gradient(to right, #beecd8 20%, #f4e2d8);
  transition: all 0.3s ease;
  height: var(--nav-bar-height);

  &.nav-sticky {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    background: #f5f5f5;
  }

  .titleBar {
    display: flex;
    align-items: center;
    height: 80rpx;
    padding: 0 40rpx;

    .search-container {
      display: flex;
      flex-grow: 1;
      max-width: 750rpx;
      margin: 0 auto;

      .search {
        display: flex;
        align-items: center;
        height: 60rpx;
        padding-left: 20rpx;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 30rpx;
        flex-grow: 1;
        transition: all 0.2s ease;

        &:active {
          transform: scale(1.03);
        }

        .icon {
          margin-right: 10rpx;
        }

        .text {
          color: #666;
          font-size: 28rpx;
        }
      }

      .ai-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 30rpx;
        padding: 0 30rpx;
        height: 60rpx;
        background: linear-gradient(225deg, #5151e5 0%, #72edf2 100%);
        border-radius: 30rpx;
        box-shadow: 0 4px 12px rgba(81, 81, 229, 0.2);
        cursor: pointer;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.96);
          box-shadow: 0 2px 4px rgba(81, 81, 229, 0.3);
        }

        .ai-icon {
          margin-right: 8rpx;
        }

        .ai-text {
          color: white;
          font-size: 28rpx;
          font-weight: 500;
        }
      }
    }
  }
}

.content-scroll {
  height: 100vh;
  overflow-y: auto;

  ::-webkit-scrollbar {
    width: 0;
    background: transparent;
  }
}

.content {
  padding-top: 20px;
  background: 
    linear-gradient(to bottom, transparent, #efefef 400px),
    linear-gradient(to right, #beecd8 20%, #f4e2d8);
  padding-bottom: 50px;
}

.swiper-container {
  padding: 0 20rpx;
  margin-top: 20rpx;
  margin-bottom: 10rpx;

  .swiper {
    width: 100%;
    height: 260rpx;

    .swiper-item {
      image {
        width: 100%;
        height: 260rpx;
        border-radius: 10px;
      }
    }
  }
}

.tag-list {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 30rpx 0;

  .tag-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10rpx 20rpx;
    border-radius: 10rpx;
    transition: all 0.2s ease;

    &:active {
      background-color: rgba(0, 0, 0, 0.05);
      transform: scale(0.98);
    }

    image {
      width: 50rpx;
      height: 50rpx;
    }

    text {
      margin-top: 10rpx;
      color: #c0c0c0;
      font-size: 14px;
    }
  }
}

// 新增热门标签及小说样式（白色背景，上下排布）
.hot-section {
  margin: 40rpx 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;

  .hot-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .hot-title {
      font-size: 34rpx;
      font-weight: 700;
      color: #333;
    }

    .hot-more {
      font-size: 28rpx;
      color: #999;
    }
  }

  .tag-scroll {
    padding: 10rpx 0;

    .tag-item {
      display: inline-block;
      padding: 16rpx 32rpx;
      margin-right: 24rpx;
      border-radius: 24rpx;
      font-size: 28rpx;
      background: #f5f5f5;
      color: #666;
      transition: all 0.2s;
      cursor: pointer;

      &.active {
        background: #ffd700;
        color: #333;
        transform: scale(1.02);
        box-shadow: 0 2px 8px rgba(255, 215, 0, 0.2);
      }

      &:active {
        transform: scale(0.98);
      }
    }
  }

  .novel-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    margin-top: 30rpx;

    .novel-item {
      display: flex;
      align-items: center;
      padding: 10rpx;
      border-radius: 10rpx;
      transition: all 0.3s ease;

      &:hover {
        background-color: #f8f8f8;
        transform: translateY(-2rpx);
      }

      .novel-cover-container {
        position: relative;
        margin-right: 20rpx;
        border-radius: 6rpx;
        overflow: hidden;
        
        .hot-rank {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 10;
          padding: 4rpx 12rpx;
          color: white;
          font-size: 24rpx;
          font-weight: bold;
          border-radius: 0 0 8rpx 0;
          box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .rank1 { background-color: #ff4444; } // 红色
        .rank2 { background-color: #ffd700; } // 金黄色
        .rank3 { background-color: #a52a2a; } // 棕色
        .rank-other { background-color: #999; } // 灰色
      }

      .novel-cover {
        width: 120rpx;
        height: 180rpx;
        display: block;
      }

      .novel-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .novel-name {
          font-size: 30rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 5rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
		
		.author {
		  font-size: 24rpx;
		  padding-bottom: 5rpx;
		}

        .novel-status {
          font-size: 24rpx;
          color: #999;
          line-height: 32rpx;
        }
      }
    }
  }

  ::-webkit-scrollbar {
    display: none;
  }
  scroll-view {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
}

.book_list {
  .title {
    margin: 20rpx;
    padding: 0 10rpx;
    font-size: 32rpx;
    font-weight: 700;
    border-left: 2px solid #ed424b;
    position: relative;
    display: flex;
    align-items: center;

    .more {
      position: absolute;
      right: 20rpx;
      top: 50%;
      margin-top: -20rpx;
      line-height: 40rpx;
      color: #999;
    }
  }

  .scroll-view {
    height: 320rpx;
    overflow: hidden;

    .scroll-view_H {
      width: 100%;
      height: 320rpx;
      white-space: nowrap;

      .scroll-view-item_H {
        width: 150rpx;
        margin: 20rpx;
        display: inline-block;

        .img_box {
          width: 100%;
          height: 200rpx;
          position: relative;
          overflow: hidden;
          border-radius: 10rpx;

          .ranking {
            position: absolute;
            left: -50rpx;
            top: -10rpx;
            width: 100%;
            text-align: center;
            z-index: 10;
            color: #fff;
            transform: rotate(-45deg);
            background-color: #4284ed;
            font-size: 24rpx;
            padding: 5rpx 0;
          }

          .ranking {
            background-color: #969ba3;

            &.one {
              background-color: #e73500;
            }

            &.two {
              background-color: #f0643a;
            }

            &.three {
              background-color: #f0c53a;
            }
          }

          .free-label {
            position: absolute;
            top: 0;
            left: 0;
            background-color: #ff4444;
            color: #fff;
            font-size: 24rpx;
            padding: 2rpx 12rpx;
            border-radius: 0 0 10rpx 0;
            z-index: 11;
            line-height: 30rpx;
          }

          image {
            width: 100%;
            height: 100%;
          }
        } 

        .name {
          font-size: 28rpx;
          line-height: 40rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-top: 10rpx;
        }

        .author {
          font-size: 24rpx;
          color: #999;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    ::-webkit-scrollbar {
      display: none;
      width: 0;
      height: 0;
    }
  }
}

// 猜你喜欢区域样式
.guess-like-section {
  margin: 40rpx 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;

  .guess-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .guess-title {
      font-size: 34rpx;
      font-weight: 700;
      color: #333;
    }

    .setting-btn {
      padding: 8rpx 24rpx;
      font-size: 24rpx;
      color: #666;

      &:hover {
        background: #f5f5f5;
      }
    }
  }

  .novel-list {
    .novel-item {
      display: flex;
      margin-bottom: 30rpx;
      padding: 10rpx;
      border-radius: 10rpx;

      .novel-cover {
        width: 120rpx;
        height: 180rpx;
        margin-right: 20rpx;
      }

      .novel-info {
        flex: 1;

        .title-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 5rpx;
        }

        .novel-name {
          font-size: 30rpx;
          font-weight: 600;
          max-width: 400rpx; // 根据实际情况调整
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .novel-score {
          color: #ff5500;
          font-size: 28rpx;
          margin-left: 15rpx; // 与标题的距离
        }

        .novel-desc {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 10rpx;
          line-height: 1.4;
          max-height: 100rpx; // 约三行高度
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }

        .bottom-row {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .novel-status {
            font-size: 24rpx;
            color: #999;
          }

          .novel-tags {
            .tag {
              display: inline-block;
              font-size: 22rpx;
              color: #666;
              background-color: #f5f5f5;
              padding: 4rpx 12rpx;
              border-radius: 12rpx;
              margin-left: 10rpx;
            }
          }
        }
      }
    }
  }
}

// 抽屉样式
.drawer {
  position: fixed;
  top: 0;
  right: 0;
  width: 400rpx;
  height: 100vh;
  background: #fff;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  z-index: 100;
  box-shadow: -2rpx 0 16rpx rgba(0,0,0,0.1);

  &.drawer-open {
    transform: translateX(0);
  }

  .drawer-content {
    height: 100%;
    padding: 40rpx 20rpx;

    .drawer-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      .drawer-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .close-btn {
        font-size: 36rpx;
        color: #999;
        cursor: pointer;
      }
    }

    .genre-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;

      .genre-item {
		display: flex;
		align-items: center;
		justify-content: center;
        padding: 16rpx 24rpx;
        border-radius: 24rpx;
        background: #f5f5f5;
        font-size: 28rpx;
        color: #666;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background: #ffd700;
          color: #333;
        }
      }
    }
  }
}
</style>